package project.web.generic;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import online.model.check.InputCheck;
import online.struts.action.UniForm;
import online.struts.mapping.RequestMapping;

import org.apache.logging.log4j.LogManager;

import project.check.range.LengthRangeCheck;
import project.svc.generic.CsvService;
import project.web.DownloadBase;
import project.web.InstanceFactory;
import core.file.ZippedLineOutputStream;
import core.util.MojiUtil;

/**
 * 汎用Csv照会
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class CsvZipAction extends DownloadBase {

	/**
	 * 主処理
	 *
	 * @param mapping ActionMappingオブジェクト
	 * @param uf 汎用フォーム
	 * @param request HttpServletRequestオブジェクト
	 * @param response HttpServletResponseオブジェクト
	 * @return 処理結果
	 */
	public String get(final UniForm uf, final HttpServletResponse response,
					final HttpServletRequest request, final RequestMapping mapping) {
		// 入力チェック
		checkInput(uf);

		try {
			//DB情報取得
			CsvService jdq = InstanceFactory.create(CsvService.class, uf);
			jdq.showTitle(super.needsTitle(uf));

			try (ZippedLineOutputStream zos = getOutputStream(response, mapping)) {
				jdq.setOutputStream(zos);

				// httpヘッダ出力
				String name = mapping.getPath().substring("/".length()) + ".zip";
				super.setHttpHeader(name, name, request, response);

				jdq.search();

				zos.finish();
			}

		} catch (final IOException ex) {
			LogManager.getLogger().info(ex.getMessage());
		}

		return null;
	}

	/**
	 * 入力チェック
	 *
	 * @param model 汎用モデル
	 */
	private void checkInput(final UniForm model) {
		InputCheck ic = InstanceFactory.create(InputCheck.class, model);
		for (final String item : model.getActionParameter().getParameterKeySet()) {
			ic.add(item, new LengthRangeCheck(0, 1024));
		}
		ic.populate();
	}

	/**
	 * OutputStream取得
	 * @param response レスポンス
	 * @param mapping マッピング
	 * @return OutputStream
	 * @throws IOException IO例外
	 */
	private ZippedLineOutputStream getOutputStream(final HttpServletResponse response,
					final RequestMapping mapping) throws IOException {
		ZippedLineOutputStream zos = new ZippedLineOutputStream(
						response.getOutputStream(), MojiUtil.CHARSET_W31J);
		zos.setEntryName(mapping.getPath().substring("/".length()) + ".csv");
		return zos;
	}
}
